package com.xhai.common.exception;

import com.xhai.common.utils.i18n.MessageUtils;
import com.xhai.common.utils.classes.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author xhai
 * @description 异常基类
 * @date 2025/6/6
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BaseException extends RuntimeException {
    /**
     * 所属模块
     */
    private String module;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误码对应的参数
     */
    private Object[] args;

    /**
     * 错误消息
     */
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args) {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage) {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args) {
        this(null, code, args, null);
    }

    public BaseException(String defaultMessage) {
        this(null, null, null, defaultMessage);
    }

    public String getI18nMessage() {
        String message = null;
        if (!StringUtils.isEmpty(code)) {
            message = MessageUtils.message(code, args);
        }
        if (message == null) {
            message = defaultMessage;
        }
        return message;
    }

    @Override
    public String getMessage() {
        String message = getI18nMessage();
        if (message == null) {
            if (!StringUtils.isEmpty(code)) {
                StringBuilder builder = new StringBuilder();
                builder.append(code);
                if (args != null && args.length > 0) {
                    builder.append(" ");
                    for (int i = 0; i < args.length; i++) {
                        builder.append("args[").append(i).append("]=").append(args[i]);
                        if (i < args.length - 1) {
                            builder.append(",");
                        }
                    }
                }

                message = builder.toString();
            }
        }
        return message;
    }
}
